import React,{useEffect,useState} from 'react';
import {
    SafeAreaView,
    StyleSheet,
    ScrollView,
    TouchableOpacity,
    View,
    Text,
    Image,ImageBackground,
    DeviceEventEmitter, TextInput,
} from 'react-native';
import Header from '../../widgets/Header';
import {getffly, numMulti, setTextThousand,cutZero} from '../../utils/common';
import screen from '../../utils/screen';
import {useStores} from '../../store';
import {observer} from 'mobx-react';
import {LGBtn} from '../../widgets/buttons';
import RequestUtil from '../../utils/RequestUtil';
import Api from '../../utils/Api';
import {AppModal} from '../../widgets/modal';
import AppEvent from '../../utils/AppEvent';
import Constants from '../../utils/Constants';
import ShadowBoxView from '../../widgets/ShadowBoxView';
import Images from '../../images/Images';

const cardW = screen.width - screen.PIXEL_60
const cardH = cardW * 108 / 130



export default observer( ({navigation})=>{


    const {userStore} = useStores()
    const [amount,setAmount] = useState('')
    const [data,setData] = useState(null)
    const [endTime,setEndTime] =  useState(0)

    useEffect(()=>{
        getStatus()
    },[])

    useEffect(()=>{
        // console.log('end time effect',endTime)
        if(endTime <= 0) return
        const timer = setInterval(()=>{
            if(endTime <= 1){
                clearInterval(timer)
            }else{
                setEndTime(endTime - 1)
            }
        },1000)
        return  ()=>{
            timer && clearInterval(timer)
        }
    },[endTime])

    const getStatus = ()=>{

        AppModal.showLoading();

        RequestUtil.get(Api.withdrawCheck).then(res=>{
            AppModal.hideTip()
            let data = res.data
            setData(data)
            if(data.status === 'reject'){
                setEndTime(data.reject.countdown)
            }

        },error=>{
            AppModal.hideTip()
            AppModal.showError(error.msg)
            console.log('widthdraw error',error)
        })

    }


    const submit = ()=>{

        if(!check()) return

        AppModal.showLoading()
        let parma = {amount:amount}
        RequestUtil.post(Api.withdrawSubmit,parma,true).then(res=>{
            getStatus()
            DeviceEventEmitter.emit(AppEvent.update_account)
            AppModal.showTip("Application submitted")
        },error=>{
            AppModal.hideTip()
            console.log(error)
            AppModal.showError(error.msg)
        })
    }

    const check = ()=>{

        console.log(JSON.stringify(data))

        let isEnable = true
        const regPos = /^\d+(\.\d+)?$/;
        let msg = ''
        if(!regPos.test(amount)){
            msg = Constants.error.invalid__number
            isEnable = false
        }else{
            if(data.normal.limitTimes.left <=0 ){
                msg = Constants.account.according_1 + data.normal.limitTimes.perDay + Constants.account.times_day
                isEnable = false
            }else if(Number(amount) < data.normal.min){
                msg = Constants.account.according_2 + Constants.appsymbol + setTextThousand(data.normal.min) + '.'
                isEnable = false
            }else if(Number(amount) > data.normal.max){
                msg = Constants.account.according_3 + Constants.appsymbol + setTextThousand(data.normal.max) + '.'
                isEnable = false
            }
        }

        if(!isEnable){
            AppModal.alert(Constants.common.note,msg,[{
                title:Constants.common.OK,
                onPress:()=>{
                    AppModal.hideAlert()
                }
            }])
        }

        console.log('withdraw:' + amount + "-" + isEnable)

        return isEnable
    }

    const reply = ()=>{
        AppModal.showLoading()
        let parma = {orderId:data.reject.orderId}
        RequestUtil.post(Api.withdrawReply,parma,true).then(res=>{
            getStatus()
        },error=>{
            AppModal.hideTip()
            console.log(error)
            AppModal.showError(error.msg)
        })
    }


    const getEndTime = (time)=>{
        let number1 = Math.ceil(time / 60);
        let number2 = Math.floor(number1 / 60);
        let number3 = number1 - number2 * 60;
        let str1 = "";
        if (Number(number2) >= 10) {
            str1 = number2;
        } else {
            str1 = "0" + number2;
        }
        let str2 = "";
        if (Number(number3) >= 10) {
            str2 = number3;
        }
        else {
            str2 = "0" + number3;
        }
        return str1 + ":" + str2
    }

     const downgrade = ()=>{
        AppModal.alert(Constants.account.warning, data.warning,[
            {
                title:Constants.account.downgrade,
                onPress:()=>{
                    AppModal.hideAlert()
                    AppModal.showLoading()
                    RequestUtil.post(Api.downgrade).then(res=>{
                        getStatus()
                        AppModal.showTip(Constants.account.successfully_downgrade)
                    },error=>{
                        AppModal.hideTip()
                        console.log(error)
                        AppModal.showError(error.msg)
                    })
                }
            },
            {
                title: Constants.account.later,
                onPress:()=>{
                    AppModal.hideAlert()
                }
            }
        ])
     }

     const renderReject = ()=>{
         let tips = "Your last application has failed";
         if (data.reject.reason && data.reject.reason != "") {
             tips += "\n" + data.reject.reason;
         }
         let isContinue = false
         if(endTime  <= 0 ){
             isContinue = true
         }

         return (
             <View style={styles.content}>
                 <Image
                     source={Images.upset}
                     style={{width:screen.PIXEL_150,height:screen.PIXEL_150,marginTop:screen.PIXEL_40}}
                 />
                 <Text style={{textAlign: 'center',fontSize: 16,color: '#FF7012',marginTop:screen.PIXEL_30}}>{tips}</Text>
                 {
                     isContinue ? (
                         <LGBtn
                            style={{width:'100%',height:screen.PIXEL_90,marginTop:screen.PIXEL_40}}
                            title={'Continue'}
                            onPress={()=> {
                                reply()
                            } }
                         />

                     ) : (
                         <View style={styles.btnGray}>
                             <Text style={{fontSize: 15,color:'#fff'}}>{getEndTime(endTime)}</Text>
                         </View>
                     )
                 }

                 <Text style={{textAlign: 'center',fontSize: 12,color: '#000',marginTop:screen.PIXEL_30}}>{Constants.account.according_6}</Text>
             </View>
         )
    }

    const renderWait = ()=>{

        const {id,amount,receive,time} = data.wait

        return (
            <ScrollView
                contentContainerStyle={{
                    paddingVertical: screen.PIXEL_20,
                    paddingHorizontal: screen.PIXEL_30,
                }}
            >
                <Image
                    source={Images.success}
                    style={{width:screen.PIXEL_150,height:screen.PIXEL_150,marginTop:screen.PIXEL_40,alignSelf:'center'}}
                />
                <Text style={{textAlign: 'center',fontSize: 16,color: '#FF7012',marginTop:screen.PIXEL_30}}>{Constants.account.according_5}</Text>
                <ImageBackground
                    style={{width:cardW,height:cardH,overflow:'hidden',justifyContent: 'flex-end',marginTop:screen.PIXEL_20}}
                    resizeMode={'contain'}
                    source={Images.card_bg}
                >
                    <View style={{flex:1,padding:screen.PIXEL_30,justifyContent: 'space-between'}}>
                        <View style={{flexDirection:'row',justifyContent: 'space-between'}}>
                            <Text style={{fontSize: 13,color:'#AEAEAE'}}>{Constants.account.application_number}</Text>
                            <Text style={{fontSize: 13,color:'#377C74' }}>{id}</Text>
                        </View>

                        <View style={{flexDirection:'row',justifyContent: 'space-between'}}>
                            <Text style={{fontSize: 13,color:'#AEAEAE'}}>{Constants.account.withdraw_amount}</Text>
                            <Text style={{fontSize: 13,color:'#377C74' }}>{amount}</Text>
                        </View>

                        <View style={{flexDirection:'row',justifyContent: 'space-between'}}>
                            <Text style={{fontSize: 13,color:'#AEAEAE'}}>{Constants.account.will_receive}</Text>
                            <Text style={{fontSize: 13,color:'#377C74' }}>{receive}</Text>
                        </View>

                        <View style={{flexDirection:'row',justifyContent: 'space-between'}}>
                            <Text style={{fontSize: 13,color:'#AEAEAE'}}>{Constants.account.submitted_on}</Text>
                            <Text style={{fontSize: 13,color:'#377C74' }}>{time}</Text>
                        </View>


                    </View>

                    <Image source={Images.dot_line}
                        // resizeMode={'contain'}
                           style={styles.dotLine}
                    />

                    <View style={{padding:screen.PIXEL_30,height:screen.PIXEL_200,alignItems:'center'}}>
                        <Text style={{fontSize: 14,color:'#ADADAD',fontWeight:'bold'}}>{'Caution'}</Text>
                        <Text style={{textAlign: 'center',fontSize: 14,color: '#ADADAD',marginTop:screen.PIXEL_20}}>{Constants.account.according_5}</Text>
                    </View>

                </ImageBackground>

                <LGBtn
                    style={{width:'100%',height:screen.PIXEL_90,marginTop:screen.PIXEL_40}}
                    title={'Back'}
                    onPress={()=> {
                        navigation.pop()
                    } }
                />

            </ScrollView>
        )
    }

    const renderClose = ()=>{
        let tips = data.close.workingHours
        return (
            <View style={styles.content}>
                <Image
                    source={Images.umbrella}
                    resizeMode={'contain'}
                    style={{width:screen.PIXEL_240,height:screen.PIXEL_160,marginTop:screen.PIXEL_100}}
                />

                <Text style={{textAlign: 'center',fontSize: 15,color: '#FF7012',marginTop:screen.PIXEL_30}}>{Constants.account.according_7}</Text>
                <Text style={{textAlign: 'center',fontSize: 13,color: '#000',marginTop:screen.PIXEL_100}}>{tips}</Text>
                <LGBtn
                    style={{width:'100%',height:screen.PIXEL_90,marginTop:screen.PIXEL_20}}
                    title={Constants.common.back}
                    onPress={()=> {
                        navigation.pop()
                    } }
                />
            </View>
        )
    }
    const getBalanceStr = ()=>{
        return setTextThousand(data.normal.balance)
    }

    const renderNormal = ()=>{
        const {level,min,max,limitTimes,fee,bankAccount,balance,minimumBalance} = data.normal
        return (
            <ScrollView
                contentContainerStyle={{
                    paddingVertical: screen.PIXEL_20,
                    paddingHorizontal: screen.PIXEL_30,
                }}
            >
                <Text style={{color:'#FF7012',fontSize:20,textAlign: 'center',marginBottom:screen.PIXEL_40}}>{`${Constants.vip.current_balance} ${Constants.appsymbol} ${getBalanceStr()} `}</Text>
                <View style={{ width: screen.width, flexDirection: 'column', alignItems: 'center', paddingTop: screen.PIXEL_20, paddingBottom: screen.PIXEL_20, backgroundColor: '#F2F2F2' }}>
                    <Text style={{ fontFamily: getffly("light"), color: '#000000', fontSize: 14, lineHeight: screen.PIXEL_30, marginTop: screen.PIXEL_20, alignSelf: 'center' }}>{Constants.account.security_deposit_lv + level + Constants.account.minimum_balance}</Text>
                    <Text style={{ fontFamily: getffly("medium"), color: '#D00000', fontSize: 20, marginTop:screen.PIXEL_10, lineHeight: screen.PIXEL_40 }}>{Constants.appsymbol + setTextThousand(cutZero("" + minimumBalance))}</Text>
                    {
                         minimumBalance !=0 && <TouchableOpacity activeOpacity={0.7} style={{marginTop:screen.PIXEL_10}} onPress={() => {
                             downgrade()
                         }} >
                             <View style={{justifyContent:'center',alignItems:'center',flexDirection:'row'}}>
                                 <Text style={{fontFamily:getffly("bold"), fontSize:14,color:'#FF2D2D',lineHeight:screen.PIXEL_40}}>{ Constants.account.withdraw_security_deposit}</Text>
                             </View>
                         </TouchableOpacity >
                    }
                </View>
                <ImageBackground
                    style={{width:cardW,height:cardH,overflow:'hidden',justifyContent: 'flex-end'}}
                    resizeMode={'contain'}
                    source={Images.card_bg}
                >
                    <View style={{flex:1,padding:screen.PIXEL_30}}>
                        <Text style={{color:'#000',fontSize:12}}>{`${Constants.account.withdraw_amount} (${Constants.appsymbol})`}</Text>
                        <TextInput
                            allowFontScaling={false}
                            placeholderTextColor={'rgba(255, 255, 255, 0.35)'}
                            placeholder={''}
                            keyboardType='numeric'
                            maxLength={30}
                            style={styles.input}
                            value={amount}
                            onChangeText={(text) => {
                                setAmount(text)
                            }}
                        />

                        <View style={{height:screen.PIXEL_130,
                            width:'100%',marginTop:screen.PIXEL_20
                        }}>
                            <Text style={{fontSize: 12,color:'#C3C3C3'}}>{Constants.account.you_current_level}
                                <Text style={{color:'#FF0000'}}>{" Lv." + level}</Text>
                                {Constants.account.single_limit}
                                <Text style={{color:'#FF0000'}}>{' ' + Constants.appsymbol + setTextThousand(min)}</Text>{Constants.account.to}
                                <Text style={{color:'#FF0000'}}>{" " + Constants.appsymbol + setTextThousand(max)}</Text>
                                {`, ${limitTimes.perDay}${Constants.account.times_day}\n${Constants.account.you_have}`}
                                <Text style={{color:'#FF0000'}}>{limitTimes.left}</Text>
                                {Constants.account.withdraw_left_today}
                                {Constants.account.fee + numMulti(fee.rate,100) + Constants.account.when_more + Constants.appsymbol+ setTextThousand(fee.condition) + ', ' + fee.fix + Constants.account.when_less + Constants.appsymbol + setTextThousand(fee.condition) + '.' }
                            </Text>
                        </View>
                    </View>


                    <Image source={Images.dot_line}
                           // resizeMode={'contain'}
                           style={styles.dotLine}
                    />

                    <View style={{padding:screen.PIXEL_30,height:screen.PIXEL_200}}>
                        <Text style={{fontSize: 13,color:'#000'}}>{Constants.account.bank_account}</Text>
                        <View style={{height:screen.PIXEL_80,flexDirection:'row',alignItems:'center',
                            paddingHorizontal:screen.PIXEL_20,backgroundColor:'rgba(101,176,169,0.16)',
                            marginTop:screen.PIXEL_20
                        }}>
                            <Image source={Images.bank_icon}
                                   resizeMode={'contain'}
                                   style={{width:screen.PIXEL_40,height:screen.PIXEL_40}}
                            />

                            <Text style={{fontSize: 20,fontWeight:'bold',marginLeft: screen.PIXEL_20}}>{bankAccount}</Text>

                        </View>
                    </View>

                </ImageBackground>

                {
                    amount.length > 0 ? (
                        <LGBtn
                            style={{width:'100%',height:screen.PIXEL_90,marginTop:screen.PIXEL_40}}
                            title={'Submit'}
                            onPress={()=> submit() }
                        />
                    ) : (
                        <View style={styles.btnGray}>
                            <Text style={{fontSize: 15,color:'#fff'}}>Submit</Text>
                        </View>
                    )
                }

            </ScrollView>

        )
    }

    const renderContent = ()=>{
        if(!data) return null

        if(data.status === 'reject'){
            return renderReject()
        }
        if(data.status === 'wait'){
            return renderWait()
        }
        if(data.status === 'close'){
            return renderClose()
        }

        return  renderNormal()
    }

    return (
        <View style={styles.container}>
            <Header title={Constants.account.withdraw} navigation={navigation}/>

            {renderContent()}



        </View>
    )
})

const styles= StyleSheet.create({
    container:{
        flex:1,
        // backgroundColor: '#fff'
    },
    content:{
        flex:1,
        paddingHorizontal:screen.PIXEL_60,
        alignItems: 'center'
    },
    input:{
        fontFamily:getffly("bold"), height: screen.PIXEL_80, width: '100%', color: '#000',
        padding: 0, fontSize: 20,backgroundColor:'rgba(101,176,169,0.16)',
        marginTop: screen.PIXEL_20,paddingHorizontal: screen.PIXEL_20
    },
    btnGray:{
        width:'100%',height:screen.PIXEL_90,marginTop:screen.PIXEL_40,borderRadius:screen.PIXEL_90/2,
        backgroundColor:'#C1C1C1',justifyContent:'center',alignItems:'center'
    },
    dotLine:{
        marginLeft:screen.PIXEL_40,
        height:1,width:cardW - screen.PIXEL_80
    }
})
